#include "texttranslator.h"
#include "requestcontenthelper.h"

#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkReply>

TextTranslator::TextTranslator(QObject* parent)
    : QNetworkAccessManager(parent)
{
    connect(this, &TextTranslator::finished, this, &TextTranslator::onReply);
}

void TextTranslator::translate(const QString& textToTranslate, Language from, Language to)
{
    m_content.textToTranslate = textToTranslate;
    m_content.from = RequestContentHelper::languageTypeToString(from);
    m_content.to = RequestContentHelper::languageTypeToString(to);
    m_content.salt = RequestContentHelper::generateSalt();
    m_content.sign = RequestContentHelper::generateSign(stringToSignFromContent());

    QMap<QString, QString> paramsWithKey;
    paramsWithKey.insert(KEY_TEXT, m_content.textToTranslate);
    paramsWithKey.insert(KEY_FROM, m_content.from);
    paramsWithKey.insert(KEY_TO, m_content.to);
    paramsWithKey.insert(KEY_APPID, m_content.appid);
    paramsWithKey.insert(KEY_SALT, m_content.salt);
    paramsWithKey.insert(KEY_SIGN, m_content.sign);

    QString url = RequestContentHelper::generateRequestContent(m_content.address, paramsWithKey);
    QNetworkRequest request;
    request.setUrl(QUrl(url));
    get(request);
}

void TextTranslator::onReply(QNetworkReply* reply)
{
    if (!reply)
        return;

    if (reply->error() != QNetworkReply::NoError)
        return;

    emit translateResult(resultInReply(reply->readAll()));
}

QString TextTranslator::stringToSignFromContent()
{
    return m_content.appid + m_content.textToTranslate + m_content.salt + m_content.pwd;
}

QString TextTranslator::resultInReply(const QByteArray& replyBytes)
{
    QJsonDocument doc = QJsonDocument::fromJson(replyBytes);
    QJsonObject object = doc.object();
    QJsonArray array = object.value(KEY_RESULT).toArray();
    if (array.isEmpty())
        return "";

    QJsonObject resultObject = array.at(0).toObject();
    return resultObject.value(KEY_DST).toString();
}
